#include "stdafx.h"
#include "ImageUtil.h"

#include "Util.h"
#include "IXIconMgr.h"
#include "XCodeDefine.h"

namespace ImageUtil
{
    ExportXSkinLib HRESULT ExtractPEIconToImageFile(IN LPCTSTR szPEFilePath, IN LPCTSTR szImagePath, IN BOOL bBigIcon)
    {
        HICON hIcon = NULL;
        UINT uResult = ::ExtractIconEx(szPEFilePath, 0, bBigIcon ? &hIcon : NULL, bBigIcon ? NULL : &hIcon, 1);
        if(uResult <= 0)
            return E_FAIL;

        XPtr<IXIconMgr> pIconMgr;
        HRESULT hResult = Util::CreateObject(&pIconMgr);
        if(FAILED(hResult))
            return E_NOINTERFACE;

        hResult = pIconMgr->SaveIcon((XICON)hIcon, szImagePath);
        return hResult;
    }

    ExportXSkinLib int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
    {
        UINT  num = 0;          // number of image encoders
        UINT  size = 0;         // size of the image encoder array in bytes

        Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL;

        Gdiplus::GetImageEncodersSize(&num, &size);
        if(size == 0)
            return -1;  // Failure

        pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
        if(pImageCodecInfo == NULL)
            return -1;  // Failure

        Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);

        for(UINT j = 0; j < num; ++j)
        {
            if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
            {
                *pClsid = pImageCodecInfo[j].Clsid;
                free(pImageCodecInfo);
                return j;  // Success
            }    
        }

        free(pImageCodecInfo);
        return -1;  // Failure
    }

}